package com.gydz.pcjjq.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory;
import com.baidu.navisdk.adapter.IBNRoutePlanManager;
import com.baidu.navisdk.adapter.IBNTTSManager;
import com.baidu.navisdk.adapter.IBaiduNaviManager;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gydz.pcjjq.R;
import com.gydz.pcjjq.app.Constants;
import com.gydz.pcjjq.base.BaseActivity;
import com.gydz.pcjjq.base.contract.main.MainContract;
import com.gydz.pcjjq.di.component.DaggerActivityComponent;
import com.gydz.pcjjq.event.CmdR4403Event;
import com.gydz.pcjjq.event.CmdT4482Event;
import com.gydz.pcjjq.event.ShowNavigationEvent;
import com.gydz.pcjjq.event.ShowPassengerInfoEvent;
import com.gydz.pcjjq.model.bean.Cmd4403Bean;
import com.gydz.pcjjq.presenter.MainPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    @BindView(R.id.tv_car_speed)
    TextView mTvCarSpeed;
    @BindView(R.id.tv_day_or_night)
    TextView mTvDayOrNight;
    @BindView(R.id.tv_discount)
    TextView mTvDiscount;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.rcy_passenger_info)
    RecyclerView mRcyPassengerInfo;
    private PassengerInfoAdapter mPassengerInfoAdapter;
    private Cmd4403Bean mCmd4403Bean = new Cmd4403Bean();
    private int[] mCnt = new int[]{0, 0, 0, 0};

    private long mExitTime;
    private boolean isClickNavigation = false;

    @Override
    protected void initInject() {
        DaggerActivityComponent.builder().build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void onBackPressedSupport() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            mExitTime = System.currentTimeMillis();
            ToastUtils.showShort("再按一次退出程序");
        } else {
            FileIOUtils.writeFileFromString(Utils.getApp().getFilesDir() + "/" + Constants.PASSENGER_INFO_JSON, JSON.toJSONString(mCmd4403Bean));
            AppUtils.exitApp();
        }
    }

    @Override
    protected void initEventAndData() {
        mPresenter.test();

        mRcyPassengerInfo.setLayoutManager(new GridLayoutManager(this, 2));
        mPassengerInfoAdapter = new PassengerInfoAdapter(mCmd4403Bean.getPassengerInfos());
        mPassengerInfoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.btn_navigation:
                        ToastUtils.showLong("导航");
                        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
                        list.add(new BNRoutePlanNode(116.30784537597782, 40.057009624099436, "百度大厦", "百度大厦", BNRoutePlanNode.CoordinateType.BD09LL));
                        list.add(new BNRoutePlanNode(116.40386525193937, 39.915160800132085, "北京天安门", "北京天安门", BNRoutePlanNode.CoordinateType.BD09LL));
                        BaiduNaviManagerFactory.getRoutePlanManager().routeplanToNavi(
                                list,
                                IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT,
                                null,
                                new Handler(Looper.getMainLooper()) {
                                    @Override
                                    public void handleMessage(Message msg) {
                                        switch (msg.what) {
                                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START:
                                                LogUtils.e("算路开始");
                                                break;
                                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
                                                LogUtils.e("算路成功");
                                                break;
                                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED:
                                                LogUtils.e("算路失败");
                                                break;
                                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI:

                                                LogUtils.e("算路成功准备进入导航");
                                                Intent intent = new Intent(MainActivity.this,
                                                        NaviGuideActivity.class);
                                                startActivity(intent);
                                                break;
                                            default:
                                                // nothing
                                                break;
                                        }
                                    }
                                });

                        break;
                    case R.id.btn_get_off:
                        ToastUtils.showLong("下车");
                        mCmd4403Bean.getPassengerInfos().get(position).setSeatStatus(Constants.ITEM_PASSENGER_INFO_2);
                        EventBus.getDefault().post(new CmdT4482Event(mCmd4403Bean.getPassengerTotal() - 1, mCmd4403Bean.getPassengerInfos().get(0).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(1).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(2).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(3).getSeatStatus(),
                                mCmd4403Bean.getPassengerInfos().get(0).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(1).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(2).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(3).getPauseStatus(), position + 1, 0, 0));
                        break;
                    case R.id.btn_pause:
                        if (mCmd4403Bean.getPassengerInfos().get(position).getPauseStatus() != 1) {
                            ToastUtils.showLong("已暂停");
                            mCmd4403Bean.getPassengerInfos().get(position).setPauseStatus(1);
                            adapter.notifyItemChanged(position);
                            EventBus.getDefault().post(new CmdT4482Event(mCmd4403Bean.getPassengerTotal(), mCmd4403Bean.getPassengerInfos().get(0).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(1).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(2).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(3).getSeatStatus(),
                                    mCmd4403Bean.getPassengerInfos().get(0).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(1).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(2).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(3).getPauseStatus(), position + 1, 1, 0));
                        } else {
                            ToastUtils.showLong("行驶中");
                            mCmd4403Bean.getPassengerInfos().get(position).setPauseStatus(0);
                            adapter.notifyItemChanged(position);
                            EventBus.getDefault().post(new CmdT4482Event(mCmd4403Bean.getPassengerTotal(), mCmd4403Bean.getPassengerInfos().get(0).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(1).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(2).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(3).getSeatStatus(),
                                    mCmd4403Bean.getPassengerInfos().get(0).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(1).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(2).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(3).getPauseStatus(), position + 1, 1, 0));
                        }
                        break;
                    case R.id.btn_get_on:
                        ToastUtils.showLong("上车");
                        mCmd4403Bean.getPassengerInfos().get(position).setSeatStatus(Constants.ITEM_PASSENGER_INFO_1);
                        EventBus.getDefault().post(new CmdT4482Event(mCmd4403Bean.getPassengerTotal() + 1, mCmd4403Bean.getPassengerInfos().get(0).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(1).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(2).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(3).getSeatStatus(),
                                mCmd4403Bean.getPassengerInfos().get(0).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(1).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(2).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(3).getPauseStatus(), position + 1, 1, 0));
                        break;
                    case R.id.btn_invoice:
                        ToastUtils.showLong("打印发票");
                        EventBus.getDefault().post(new CmdT4482Event(mCmd4403Bean.getPassengerTotal(), mCmd4403Bean.getPassengerInfos().get(0).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(1).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(2).getSeatStatus(), mCmd4403Bean.getPassengerInfos().get(3).getSeatStatus(),
                                mCmd4403Bean.getPassengerInfos().get(0).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(1).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(2).getPauseStatus(), mCmd4403Bean.getPassengerInfos().get(3).getPauseStatus(), position + 1, 0, 1));
                        break;
                }
            }
        });
        mRcyPassengerInfo.setAdapter(mPassengerInfoAdapter);


        if (FileUtils.isFileExists(Utils.getApp().getFilesDir() + "/" + Constants.PASSENGER_INFO_JSON)) {
            Cmd4403Bean cmd4403Bean = JSON.parseObject(FileIOUtils.readFile2String(Utils.getApp().getFilesDir() + "/" + Constants.PASSENGER_INFO_JSON), Cmd4403Bean.class);
            if (cmd4403Bean != null) {
                mCmd4403Bean = cmd4403Bean;
            }
            updateView();
        }

        initBaiduNavi();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageCmdR4403Event(CmdR4403Event cmdR4403Event) {
        int passengerTotal = 0;
        for (int i = 0; i < 4; i++) {
            if (!mCmd4403Bean.getPassengerInfos().get(i).getLastCmdContent().equals(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).toString())) {
                mCmd4403Bean.getPassengerInfos().get(i).setPassengerNumber(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getPassengerNumber());
                mCmd4403Bean.getPassengerInfos().get(i).setMileage(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getMileage());
                mCmd4403Bean.getPassengerInfos().get(i).setWaitTime(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getWaitTime());
                mCmd4403Bean.getPassengerInfos().get(i).setShouldPay(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getShouldPay());
                mCmd4403Bean.getPassengerInfos().get(i).setRealPay(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getRealPay());
                mCmd4403Bean.getPassengerInfos().get(i).setSeatStatus(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).getSeatStatus());
                mCmd4403Bean.getPassengerInfos().get(i).setLastCmdContent(cmdR4403Event.getCmd4403Bean().getPassengerInfos().get(i).toString());
                mCnt[i] = 0;
            } else {
                mCnt[i]++;
                if (mCnt[i] > 3) {
                    mCnt[i] = 0;
                    if (mCmd4403Bean.getPassengerInfos().get(i).getSeatStatus() == Constants.ITEM_PASSENGER_INFO_1 && mCmd4403Bean.getPassengerInfos().get(i).getPauseStatus() != 1) {
                        mCmd4403Bean.getPassengerInfos().get(i).setSeatStatus(Constants.ITEM_PASSENGER_INFO_2);
                    }
                }
            }
            if (mCmd4403Bean.getPassengerInfos().get(i).getSeatStatus() == Constants.ITEM_PASSENGER_INFO_1) {
                passengerTotal++;
            }
        }
        mCmd4403Bean.setCurrentTime(cmdR4403Event.getCmd4403Bean().getCurrentTime());
        mCmd4403Bean.setPrice(cmdR4403Event.getCmd4403Bean().getPrice());
        mCmd4403Bean.setDiscount(cmdR4403Event.getCmd4403Bean().getDiscount());
        mCmd4403Bean.setCarSeatState(cmdR4403Event.getCmd4403Bean().getCarSeatState());
        mCmd4403Bean.setCarSpeed(cmdR4403Event.getCmd4403Bean().getCarSpeed());
        mCmd4403Bean.setCarDrivingState(cmdR4403Event.getCmd4403Bean().getCarDrivingState());
        mCmd4403Bean.setPassengerTotal(passengerTotal);

        updateView();
    }

    @SuppressLint("DefaultLocale")
    private void updateView() {
//        if (mCmd4403Bean.getCarSeatState() == 0 && mNavigationFragment.isHidden()) {
//            showHideFragment(mNavigationFragment, mPassengerInfoFragment);
//        } else if (mCmd4403Bean.getCarSeatState() == 1 && mPassengerInfoFragment.isHidden() && !isClickNavigation){
//            showHideFragment(mPassengerInfoFragment, mNavigationFragment);
//        }
        mPassengerInfoAdapter.setNewData(mCmd4403Bean.getPassengerInfos());
        mTvCarSpeed.setText(mCmd4403Bean.getCarSpeed() == 1 ? "低速" : "常速");
        mTvDayOrNight.setText("白天");
        mTvDiscount.setText(String.format("当前折扣:%d%%", mCmd4403Bean.getDiscount()));
        mTvPrice.setText(String.format("单价:%.2f元", mCmd4403Bean.getPrice() / 100f));
        FileIOUtils.writeFileFromString(Utils.getApp().getFilesDir() + "/" + Constants.PASSENGER_INFO_JSON, JSON.toJSONString(mCmd4403Bean));
    }

    private void initBaiduNavi() {
        BaiduNaviManagerFactory.getBaiduNaviManager().init(this,
                Environment.getExternalStorageDirectory().toString(), "pcjjq", new IBaiduNaviManager.INaviInitListener() {

                    @Override
                    public void onAuthResult(int status, String msg) {
                        String result;
                        if (0 == status) {
                            result = "key校验成功!";
                        } else {
                            result = "key校验失败, " + msg;
                        }
                        LogUtils.e(result);
                    }

                    @Override
                    public void initStart() {
                        LogUtils.e("百度导航引擎初始化开始");
                    }

                    @Override
                    public void initSuccess() {
                        LogUtils.e("百度导航引擎初始化成功");
                        // 初始化tts
                        initTTS();
                    }

                    @Override
                    public void initFailed() {
                        LogUtils.e("百度导航引擎初始化失败");
                    }
                });
    }

    private void initTTS() {
        // 使用内置TTS
        BaiduNaviManagerFactory.getTTSManager().initTTS(this,
                Environment.getExternalStorageDirectory().toString(), "pcjjq", "11484665");

        // 不使用内置TTS
//         BaiduNaviManagerFactory.getTTSManager().initTTS(mTTSCallback);

        // 注册同步内置tts状态回调
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedListener(
                new IBNTTSManager.IOnTTSPlayStateChangedListener() {
                    @Override
                    public void onPlayStart() {
                        LogUtils.e("ttsCallback.onPlayStart");
                    }

                    @Override
                    public void onPlayEnd(String speechId) {
                        LogUtils.e("ttsCallback.onPlayEnd");
                    }

                    @Override
                    public void onPlayError(int code, String message) {
                        LogUtils.e("ttsCallback.onPlayError");
                    }
                }
        );

        // 注册内置tts 异步状态消息
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedHandler(
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        LogUtils.e("ttsHandler.msg.what=" + msg.what);
                    }
                }
        );
    }


}
